<template>
  <div>
    <SearchContainer @reset="() => formRef.resetFields()" @search="getData">
      <a-form ref="formRef" class="form-style-flex" :model="formState">
        <a-form-item name="dateRange" label="手术日期" class="w-72">
          <a-range-picker v-model:value="formState.dateRange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item name="pyjm" label="" class="w-52 ml-2">
          <a-input v-model:value="formState.pyjm" placeholder="姓名/助记码/卡号/住院号" />
        </a-form-item>
        <a-form-item name="bedCode" label="" class="w-52 ml-2">
          <a-input v-model:value="formState.bedCode" placeholder="床位号" />
        </a-form-item>
        <a-form-item name="oprName" label="" class="w-52 ml-2">
          <a-input v-model:value="formState.oprName" placeholder="手术名称" />
        </a-form-item>
        <a-form-item name="status" label="" class="ml-4">
          <a-radio-group v-model:value="formState.status">
            <a-radio value="">全部</a-radio>
            <a-radio value="0">未安排</a-radio>
            <a-radio value="1">已安排</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </SearchContainer>
    <a-card class="mt-2">
      <div class="flex justify-between mb-2">
        <!-- <a-button class="mb-2" type="primary" @click="onAdd"> 新增 </a-button> -->
        <div>
          <div class="absolute top-[-9999px] hidden">
            <a-button ref="printMe" v-print="{ id: 'printMe' }">手术安排单</a-button>
            <PrintView id="printMe" :print-data="printData" />
          </div>
          <div class="absolute top-[-9999px] hidden">
            <a-button ref="printNoticeMe" v-print="{ id: 'printNoticeMe' }">手术通知单</a-button>
            <NoticePrint id="printNoticeMe" :print-data="printNoticeData" />
          </div>
          <a-button class="ml-2" type="primary" ghost @click="onPrint"><BaseIcon name="PrinterOutlined" :loading="printLoading1" /> 手术安排单 </a-button>
          <a-button class="ml-2" type="primary" ghost @click="onPrintNotice"> <BaseIcon name="PrinterOutlined" :loading="printLoading2" />手术通知单 </a-button>
          <BaseExport class="ml-2" type="手术统计" name="手术统计" code="001035" :search-params="formState">导出</BaseExport>
        </div>
        <!-- <a-button class="ml-2" type="primary" disabled ghost @click="onSaveAll"> 保存 </a-button> -->
        <a-button class="ml-2" type="primary" @click="onSubmitAll"> 全部确认 </a-button>
      </div>
      <BaseTable :columns="columns" :loading="loading" :data-source="tableData" fill :row-class-name="getRowClass" :scroll="{ x: 2850 }" :extra-height="40">
        <!-- 自定义表头 -->
        <template #headerCell="{ column }">
          <div v-if="column.required" class="-m-2">
            <div class="p-2"><span class="text-red-600">*</span> {{ column.title }}</div>
          </div>
          <div v-if="column.subTitle" class="-m-2">
            <div class="border-b p-2">{{ column.title }}</div>
            <div class="p-2">{{ column.subTitle }}</div>
          </div>
        </template>
        <template #bodyCell="{ column, record, text, index }">
          <template v-if="column.dataIndex === 'xh'"> {{ index + 1 }} </template>
          <template v-if="column.dataIndex === 'status'">
            <a-tag v-if="text === '0'" color="blue">未安排</a-tag>
            <a-tag v-if="text === '1'" color="success">已安排</a-tag>
            <a-tag v-if="text === '2'" color="red">作废</a-tag>
            <a-tag v-if="text === '4'" color="red">手术中</a-tag>
            <a-tag v-if="text === '3'" color="blue">待手术</a-tag>
            <a-tag v-if="text === '5'" color="success">已手术</a-tag>
            <a-tag v-if="text === '6'" color="success">已转出</a-tag>
            <a-tag v-if="text === '7'" color="blue">未安排</a-tag>
          </template>
          <template v-if="column.dataIndex === 'oprDate'">
            <EditCell label="手术日期">
              <a-date-picker v-model:value="record.oprDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="onSave(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'brName'">
            {{ record.brName }} <span class="text-grey text-xs">{{ record.brXb }} {{ record.brAge }}</span>
          </template>
          <template v-if="column.dataIndex === 'oprTime'">
            <EditCell label="手术时间">
              <a-time-picker v-model:value="record.oprTime" format="HH:mm" value-format="HH:mm" @change="onSave(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'oprRoomName'">
            <EditCell label="手术房间">
              <!-- bqid: 'BQ00000022', -->
              <SelectTable
                v-model:value="record.oprRoomName"
                type="床位"
                :table-width="400"
                :row-disabled="(row) => row.status === 2 || row.status === 1"
                :search-params="{ bqlb: 'QYLB004', wardName: '手术病区' }"
                @select="onSelect('oprRoomId', $event.id, 'oprRoomName', $event.bedCode, record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'oprDoctorName'">
            <div>
              <EditCell label="手术医生">
                <!-- 手术医生 -->
                <div class="!h-1/2 !border-b">
                  <SelectTable
                    v-model:value="record.oprDoctorName"
                    type="医生"
                    @select="onSelect('oprDoctor', $event.empId, 'oprDoctorName', $event.empName, record)"
                  />
                </div>
                <!-- 麻醉医生 -->
                <SelectTable
                  v-model:value="record.anaesDoctorName"
                  class="!h-1/2"
                  type="医生"
                  @select="onSelect('anaesDoctor', $event.empId, 'anaesDoctorName', $event.empName, record)"
                />
              </EditCell>
            </div>
          </template>
          <template v-if="column.dataIndex === 'firstNurseName'">
            <EditCell label="一助">
              <!-- 一助 -->
              <div class="!h-1/2 !border-b">
                <SelectTable
                  v-model:value="record.firstNurseName"
                  type="医生"
                  :search-params="{ emplb: '2' }"
                  @select="onSelect('firstNurse', $event.empId, 'firstNurseName', $event.empName, record)"
                />
              </div>
              <!-- 二助 -->
              <SelectTable
                v-model:value="record.secondNurseName"
                type="医生"
                class="!h-1/2"
                :search-params="{ emplb: '2' }"
                @select="onSelect('secondNurse', $event.empId, 'secondNurseName', $event.empName, record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'tourNurseName'">
            <EditCell label="巡回护士">
              <!-- 巡回护士 -->
              <div class="!h-1/2 !border-b">
                <SelectTable
                  v-model:value="record.tourNurseName"
                  type="医生"
                  :search-params="{ emplb: '2' }"
                  @select="onSelect('tourNurse', $event.empId, 'tourNurseName', $event.empName, record)"
                />
              </div>
              <!-- 器械护士 -->
              <SelectTable
                v-model:value="record.instrumenttNurseName"
                type="医生"
                class="!h-1/2"
                :search-params="{ emplb: '2' }"
                @select="onSelect('instrumenttNurse', $event.empId, 'instrumenttNurseName', $event.empName, record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-button v-if="record.status === '0' && record.oprPath === 3" size="small" type="link" @click="onEdit(record)">修改</a-button>
            <a-button v-if="record.status === '0'" :disabled="!isCanConfirm(record)" size="small" type="link" @click="onClickStatus(record, 1)">确认</a-button>
            <!-- <a-button v-if="record.status !== '0'" confirm-text="撤销?" size="small" type="text" danger @click="onClickStatus(record, 0)">撤销</a-button> -->
            <BaseButton
              v-if="record.status === '1' && record.signStatus === '1'"
              confirm-text="确认撤销?"
              size="small"
              type="text"
              danger
              @click="onClickStatus(record, 0)"
            >
              撤销
            </BaseButton>
            <BaseButton
              v-if="record.status === '0' && record.oprPath === 3"
              confirm-text="确认作废?"
              size="small"
              type="text"
              danger
              @click="onClickStatus(record, 2)"
            >
              作废
            </BaseButton>
          </template>
        </template>
      </BaseTable>
    </a-card>
    <Edit v-model:open="openEditModal" :row-data="rowData" @success="getData" />
  </div>
</template>
<script setup>
import { h, ref } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import { getSystemConfig } from '@/utils/systemConfig'
import Edit from './Edit.vue'
import PrintView from './components/PrintView.vue'
import NoticePrint from './components/NoticePrint.vue'

const rowData = ref()
const printData = ref({})
const printNoticeData = ref({})
const printMe = ref()
const printNoticeMe = ref()
const openEditModal = ref(false)
const formRef = ref()
const formState = ref({
  status: '',
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().add('6', 'day').format('YYYY-MM-DD')]
})
const onEdit = (record) => {
  openEditModal.value = true
  rowData.value = record
}
// const onAdd = () => {
//   openEditModal.value = true
//   rowData.value = {}
// }
const onSubmitAll = async () => {
  const aptmLshList = tableData.value.map((item) => item.aptmLsh)
  const { code, msg } = await post('/oprOperation/opr/doUpdateOperationAppoiementStatusAll', {
    aptmLshList: aptmLshList
  })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  getData()
}
const isCanConfirm = (record) => {
  return record.oprDate && record.oprTime && record.oprRoomName
}
// 确认(1)撤销(0)作废(2)
const onClickStatus = async (row, status) => {
  const { code, msg } = await post('/oprOperation/opr/doUpdateOperationAppoiementStatus', {
    status,
    aptmLsh: row.aptmLsh
  })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  getData()
}

const customRender = ({ record, column }) => {
  const dataValue = record[column.dataIndex]
  const subDataValue = record[column.subDataIndex]
  return h('div', { class: 'w-full' }, [
    h('div', { class: 'border-b p-2 h-10 truncate', title: dataValue }, dataValue),
    h('div', { class: 'p-2 h-10 truncate', title: subDataValue }, subDataValue)
  ])
}

const columns = [
  { title: '序号', dataIndex: 'xh', width: 50 },
  { title: '状态', dataIndex: 'status', width: 80 },

  { title: '手术日期', dataIndex: 'oprDate', width: 100, required: true },
  { title: '手术时间', dataIndex: 'oprTime', width: 100, required: true },
  { title: '手术房间', dataIndex: 'oprRoomName', width: 100, required: true },
  {
    title: '床位号',
    dataIndex: 'lastBedCode',
    width: 100
  },
  {
    title: '住院号/卡号',
    dataIndex: 'admissionCode',
    width: 130
  },
  { title: '姓名', dataIndex: 'brName', width: 130 },
  { title: '来源', dataIndex: 'oprPathStr', width: 80 },
  { title: '部位', dataIndex: 'oprAptmParts', width: 80 },
  { title: '手术名称', dataIndex: 'oprName', width: 180 },
  {
    title: '联合手术1',
    dataIndex: 'jointOprName1',
    subTitle: '联合手术2',
    subDataIndex: 'jointOprName2',
    width: 130,
    customCell: () => ({ class: '!p-0' }),
    customRender
  },
  {
    title: '联合手术3',
    dataIndex: 'jointOprName3',
    subTitle: '联合手术4',
    subDataIndex: 'jointOprName4',
    width: 130,
    customCell: () => ({ class: '!p-0' }),
    customRender
  },
  {
    title: '联合手术5',
    dataIndex: 'jointOprName5',
    subTitle: '联合手术6',
    subDataIndex: 'jointOprName6',
    width: 130,
    customCell: () => ({ class: '!p-0' }),
    customRender
  },
  { title: '嘱托', dataIndex: 'advMemo', subTitle: '特殊需求', subDataIndex: 'specRequirements', customCell: () => ({ class: '!p-0' }), customRender },
  { title: '手术医生', dataIndex: 'oprDoctorName', subTitle: '麻醉医生', subDataIndex: 'anaesDoctorName', customCell: () => ({ class: '!p-0' }), customRender },
  { title: '一助', dataIndex: 'firstNurseName', subTitle: '二助', subDataIndex: 'secondNurseName', customCell: () => ({ class: '!p-0' }), customRender },
  {
    title: '巡回护士',
    dataIndex: 'tourNurseName',
    subTitle: '器械护士',
    subDataIndex: 'instrumenttNurseName',
    customCell: () => ({ class: '!p-0' }),
    customRender
  },
  {
    title: '台次',
    dataIndex: 'serialNumber',
    subTitle: '麻醉方式',
    subDataIndex: 'anaesName',
    customCell: () => ({ class: '!p-0' }),
    customRender
  },
  {
    title: '手术等级',
    dataIndex: 'oprLevelName',
    subTitle: '手术入路',
    width: 95,
    subDataIndex: 'approachName',
    customCell: () => ({ class: '!p-0' }),
    customRender
  },
  {
    title: '手术分类',
    dataIndex: 'oprTypeName',
    subTitle: '切口等级',
    width: 95,
    subDataIndex: 'cutLevelName',
    customCell: () => ({ class: '!p-0' }),
    customRender
  },
  // { title: '麻醉方式', dataIndex: 'anaesName' },

  { title: '心电监护', dataIndex: 'isEcgStr', subTitle: '复发', subDataIndex: 'isRecurrenceStr', customCell: () => ({ class: '!p-0' }), customRender },
  {
    title: '预约医生/预约科室',
    dataIndex: 'aptmDoctorName',
    width: 160,
    subTitle: '预约时间',
    subDataIndex: 'aptmTime',
    customCell: () => ({ class: '!p-0' }),
    customRender
  },
  { title: '国家医保编码', dataIndex: 'nmiCode', width: 180 },
  { title: '操作', dataIndex: 'action', fixed: 'right', width: 160 }
]

const { loading, tableData, getData } = useTable({
  url: '/oprOperation/opr/getOperationAppointmentList',
  immediate: true,
  pagination: false,
  formatParams: () => {
    return {
      stdate: formState.value.dateRange?.[0],
      eddate: formState.value.dateRange?.[1],
      statuss: ['0', '1', '3', '4', '5', '6'],
      ...formState.value
    }
  },
  formatResult: (result = []) => {
    return result.map((item) => {
      return {
        ...item,
        admissionCode: item.oprPath === 1 ? item.admissionCode : item.brId,
        aptmDoctorName: item.aptmDoctorName + '/' + (item.aptmDeptName || ''),
        isEcgStr: item.isEcg ? '是' : '否',
        isRecurrenceStr: item.isRecurrence ? '是' : '否',
        oprPathStr: ['门诊', '住院', '', '手术'][item.oprPath] //手术来源;0：门诊|1：住院 |3手术室
      }
    })
  }
})

const getRowClass = (record) => {
  return record.status === '0' ? '' : 'table-row-readonly-not-last'
}
//保存手术
const onSave = async (row) => {
  const res = await post('/oprOperation/opr/doSaveOperationRecordInfo', row)
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg)
  getData()
}
// const onSaveAll = async () => {
//   //
// }
const onSelect = (key1, value1, key2, value2, row) => {
  row[key1] = value1
  row[key2] = value2
  onSave(row)
}
const printLoading1 = ref(false)
const printLoading2 = ref(false)
// 手术安排单
const onPrint = async () => {
  printLoading1.value = true
  const { code, msg, data } = await post('/oprOperation/oprPrint/surgicalSchedulePrint', {
    stdate: formState.value.dateRange?.[0],
    eddate: formState.value.dateRange?.[1],
    oprName: formState.value.oprName,
    status: formState.value.status,
    pyjm: formState.value.pyjm
  })
  printLoading1.value = false
  if (code !== 0) return message.error(msg)
  if (getSystemConfig('NAVYHIS_MODE') === '1') {
    printData.value = JSON.parse(data)

    // return
    setTimeout(() => {
      setPrintSize('A4', 'landscape')
      printMe.value.$el.click()
    }, 1000)
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
}
const someAsyncOperation = (value) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      printNoticeData.value = value ? JSON.parse(value) : {}
      printNoticeMe.value.$el.click()
      resolve()
    }, 100)
  })
}
// 手术通知单
const onPrintNotice = async () => {
  printLoading2.value = true
  // const { code, msg, data } = await post('/oprOperation/oprPrint/surgicalNoticesPrint', {
  const { code, msg, data } = await post('/oprOperation/oprPrint/surgicalNoticesPrints', {
    stdate: formState.value.dateRange?.[0],
    eddate: formState.value.dateRange?.[1],
    oprName: formState.value.oprName,
    status: formState.value.status,
    pyjm: formState.value.pyjm
  })
  printLoading2.value = false
  if (code !== 0) return message.error(msg)
  const resourceData = []
  for (const key in data) {
    resourceData.push(data[key])
  }
  for (let i = 0; i < resourceData.length; i++) {
    if (getSystemConfig('NAVYHIS_MODE') === '1') {
      await someAsyncOperation(resourceData[i])
    } else {
      window.openExe?.rpt(resourceData[i]) //调用winform打印
    }
  }

  // if (getSystemConfig('NAVYHIS_MODE') === '1') {
  //   const resourceData = JSON.parse(data)
  //   if (resourceData?.printData?.detail?.length <= 0) return message.warning('暂无要打印的手术通知单')
  //   const timeData = resourceData?.printData?.detail?.map((item) => {
  //     if (item.sssj) return item.sssj
  //   })
  //   const uniqueArr = Array.from(new Set(timeData)) || []
  //   uniqueArr.forEach((item) => {
  //     printNoticeData.value = resourceData?.printData?.detail?.filter((it) => {
  //       return it.sssj === item
  //     })
  //     setTimeout(() => {
  //       printNoticeMe.value.$el.click()
  //     }, 100)
  //   })
  // } else {
  //   window.openExe?.rpt(data) //调用winform打印
  // }
}
</script>
